package com.halden.mycache.support.EvictStrategy.impl;

import com.halden.mycache.support.EvictStrategy.EvictStrategy;
import com.halden.mycache.support.EvictStrategy.ICacheEvictContext;
import com.halden.mycache.core.Impl.CacheValue;

import java.util.Date;
import java.util.HashSet;
import java.util.Random;
import java.util.Set;

/**
 * @Author: halden
 * @Data:2023/2/3 19:03
 * @Description: 为了代码复用使用抽象类
 */
public abstract class AbstractEvictStrategy<K,V> implements EvictStrategy<K,V> {

    public CacheValue visit(ICacheEvictContext<K, V> context) {
        CacheValue<V> cacheValue = context.getValue();
        long now = new Date().getTime();
        double add = 10000 / (now - cacheValue.getLastUseTime() + 1);
        cacheValue.setVisitFrequency(cacheValue.getVisitFrequency() + add);
        cacheValue.setLastUseTime(now);
        // 返回修改后的结果
        return cacheValue;
    }

    /**
     * 随机生成[0,num)范围内的5个不同的随机数
     * @param num
     * @return
     */
    public Integer[] random5Num(int num){
        Random random = new Random();
        Set<Integer> set = new HashSet<>();
        for (int i = 0; i < 5; i++){
            int rNum = random.nextInt(num);
            while (set.contains(rNum)){
                rNum = random.nextInt(num);
            }
            set.add(rNum);
        }
        return set.toArray(new Integer[5]);
    }

}
